#include "base_time.h"

#ifndef UGLY_HACK_FOR_THOSE_WHO_DONT_KNOW_HOWTO_INSTALL_SDL
#include <SDL/SDL.h>
#else
#include <SDL.h>
#endif

#include "base_memory.h"

float time_get(void) // recupere le temp en sec depuis le debut prog
{
    static int _time_initialized;
    static float _time_offset;
    if(_time_initialized == 0)
    {
        _time_initialized = 1;
        _time_offset = SDL_GetTicks() / 1000.;
    }
    return SDL_GetTicks() / 1000. - _time_offset;
}

void time_sleep(float dT)//suspendre le prog pendant dt sec
{
    SDL_Delay(dT * 1000);
    return;
}


//-----------------------------------------------------------------------------
// Clock
//-----------------------------------------------------------------------------


Clock* clock_new(void)// cree une nouvelle horloge
{
    Clock *t;
    t=(Clock*)mem_allocate(sizeof(Clock));
    t->timeStarted=0;
    t->isPaused=1;
    t->isStopped=1;
    return t;
}

void clock_delete(Clock *t)//detruit la memoire prise par de l'horloge
{
    mem_free(t);
}

float clock_get(Clock *t)// recupere le temp de l'horloge
{
    if(t->isStopped)
        { return 0; }
    float d;
    if(t->isPaused)
    {
        return t->timePause - t->timeAbsolute;
        d=t->timeStarted;
    }
    else
        d=t->timeStarted+time_get()-(t->timeAbsolute);
    return d;
}

void clock_start(Clock *t)//demarre l'horloge
{

    if(t->isStopped)
        {t->timeAbsolute=time_get();}
    else
        {
            t->timePause=clock_get(t);
            t->timeAbsolute= (time_get() - t->timePause);
        }
    t->isPaused=0;
    t->isStopped=0;

}

void clock_pause(Clock *t)//Met en pause
{
    t->timePause=time_get();
    t->isPaused=1;
}

void clock_reset(Clock *t)//renitialise
{
    t->timeStarted=0;
    t->isStopped=1;
    t->timePause=0;
    t->isPaused=1;
}
